package com.example.hellodemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.hellodemo.fragement.AFragement;
import com.example.hellodemo.fragement.BFragement;

public class ContainsActivity extends AppCompatActivity {
    private Button containsBtn;
    private TextView textView;
    private AFragement aFragement;
    private BFragement bFragement;
    static int num = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contains);

        containsBtn = findViewById(R.id.container_b);
        containsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bFragement == null){
                    bFragement = new BFragement();
                }

                /*  addToBackStack  当我添加新的Fragement 时 如何 我们想点返回键回到之前的状态 而不是退出Activity 可以用这个方法
                    在Fragement视图切换时，如果用 hide A, add B 则 AFragement渲染的视图对象还是在的， 返回时还是原状态 不会调用onCreateView 方法
                    如果 用 replace 将 B替换成A 则AFragement绑定的View对象则释放。 返回时，重新创建，调用不会调用onCreateView。

                * */
                getSupportFragmentManager().beginTransaction().replace(R.id.container_f,bFragement).addToBackStack(null).commitAllowingStateLoss();
                getSupportFragmentManager().beginTransaction().hide(aFragement).add(R.id.container_f,bFragement).addToBackStack(null).commitAllowingStateLoss();
            }
        });

        // 实例化AFragement
        aFragement = new AFragement();
        Bundle bundle = new Bundle();
        bundle.putString("title","船只");
        aFragement.setArguments(bundle);
        //Fragement添加到Activity中 记得commit
        getSupportFragmentManager().beginTransaction().add(R.id.container_f,aFragement).commitAllowingStateLoss();
    }

    public void setText(String str) {
        this.textView.setText(str);
    }
}
